import React, { useEffect, useState } from 'react';

const Index = () => {
    const [msg,setMsg] = useState("")
    const [list,setList] = useState([])
    const getStorage = ()=>{
      let list = JSON.parse(localStorage.getItem("hooks")) || []
      setList(list)
    }
    useEffect(()=>{
        getStorage()
    },[])
    const handleChange= (e)=>{
        setMsg(e.target.value)
    }
    const toDo = (e)=>{
        if(e.keyCode===13){
            var obj = {
                msg:msg,
                checked:false,
                id:Math.random()
            }
            var s = list.findIndex(item=>item.msg===obj.msg)
            if(s===-1&&obj.msg!=""){
                list.push(obj)
            }
            setStorage()
            setList(list)
            setMsg("")
        }
    }
    const toChange = (index)=>{
        list[index].checked = !list[index].checked;
        setStorage()
        setList(()=>{
            return [...list]
        })
    }
    const toDelete = (index)=>{
        list.splice(index,1)
        setStorage()
        setList(()=>{
            return [...list]
        })
    }
    const setStorage = ()=>{
        localStorage.setItem("hooks",JSON.stringify(list))
    }
    const ListItem = list.map((item,index)=>{
        if(item.checked===false)
        {
            return (
                <div key={item.id}>
                    <input type="checkbox" name="" id="" checked={item.checked} onChange={()=>toChange(index)}/>
                    {item.msg}
                    <button onClick={()=>toDelete(index)}>删除</button>
                </div>
            )
        }
    })
    const DoneItem = list.map((item,index)=>{
        if(item.checked===true)
        {
            return (
                <div key={item.id}>
                    <input type="checkbox" name="" id="" checked={item.checked} onChange={()=>toChange(index)}/>
                    {item.msg}
                    <button onClick={()=>toDelete(index)}>删除</button>
                </div>
            )
        }
    })
    return (
        <div>
            <h1>TodoList</h1>
            <input type="text" onChange={handleChange} value={msg} onKeyUp={toDo}/>
            <h2>进行中</h2>
                {ListItem}
            <h2>已完成</h2>
                {DoneItem}
        </div>
    );
}

export default Index;
